import {
	serverUrl2
} from '../const'

class Socket {
	constructor() {
		this.socketTask = null // socket 实例
		this.isConnect = false // 是否连接成功
	}
	connect(token) {
		if (this.isConnect && token) return
		this.socketTask = uni.connectSocket({
			url: 'ws://' + serverUrl2 + '/myHandler/token=' + token,
			success: () => {
				this.isConnect = true
			},
			fail: () => {
				this.isConnect = false
			}
		})
		this.init()
	}
	init() {
		this.socketTask.onOpen(() => {
			console.log('Socket 创建了');
		})
		this.socketTask.onMessage(res => {
			console.log('收到消息')
			uni.$emit('message', res)
		})
		this.socketTask.onClose(() => {
			this.isConnect = false
			this.socketTask = null
			console.log('Socket 关闭了')
		})
	}
	close() {
		if (!this.isConnect) return
		this.socketTask.close()
	}
}

export default new Socket()
